package com.superhelper.app.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.app.common.Consts;
import com.superhelper.app.controller.base.AbstractController;
import com.superhelper.app.domain.Admin;
import com.superhelper.app.domain.Resp;
import com.superhelper.app.service.JHSmsHandler;
import com.superhelper.common.utils.CryptUtil;

/**
 * 短信验证接口
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/v1/sms")
public class SmsVerifyController extends AbstractController {

	private final String TPL_VALUE = "#code#=%s";
	private Map<String, String> MSG_TEMPLATE = new HashMap<String, String>() {

		private static final long serialVersionUID = -342940937399419088L;
		{
			put("register", "36567");// 模板ID
			put("forgetPwd", "36568");
		}
	};

	@Autowired
	private JHSmsHandler smsService;

	/**
	 * 获取短信验证码(通过手机号)
	 * 
	 * @param phone
	 * @param target
	 *            register:注册 forgetPwd:忘记密码
	 * @return
	 */
	@RequestMapping("/code")
	@ResponseBody
	public Resp codeByPhone(@RequestParam String phone,
			@RequestParam String target) {
		String code = null;
		Admin user = null;
		switch (target) {
		case "register":
			user = adminService.getAdminByUsername(phone);
			if (user != null) {// 手机已经被注册
				return resp(Consts.Code.USER_PHONE_EXISTS,"手机号已经被注册");
			}
			code = send("register", phone, 180);

			break;
		case "forgetPwd":
			user = adminService.getAdminByUsername(phone);
			// 手机号码不存在
			if (user == null) {
				return resp(Consts.Code.USER_NOT_EXISTS,"账号不存在！");
			}
			code = send("forgetPwd", phone, 180);
			break;

		default:

		}
		if (code == null) {
			return fail();
		}
		return success();
	}

	private String send(String type, String phone, int expir) {
		String code = RandomStringUtils.randomNumeric(6);
		boolean result = false;
		String redisCode = redisService.getString(phone + "_" + type);
		if (StringUtils.isNotBlank(redisCode)) {
			return CryptUtil.md5(redisCode);
		}
		result = smsService.send(phone, MSG_TEMPLATE.get(type),
				String.format(TPL_VALUE, code));
		if (result) {
			redisService.setString(phone + "_" + type, code, expir);
		} else {
			return null;
		}
		return CryptUtil.md5(code);
	}
}
